﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Action.SPI;
using T.FAS.Runtime.Base.Entity;

namespace T.FAS.Runtime.Action.Engine
{
    public static class ActionExecuteEngineProvider
    {
        private static IActionExecuteEngine actionExecute;

        private static readonly object syncObject = new object();

        public static IActionExecuteEngine GetSingletonEngine()
        {
            if (actionExecute == null)
            {
                lock (syncObject)
                {
                    if (actionExecute == null)
                    {
                        actionExecute = new ActionExecuteEngine();
                    }
                }
            }

            return  actionExecute;
        }

        public static IActionExecuteEngine CreateTransistEngine(ActionExecContext context)
        {
            IActionExecuteEngine engine = null;
            var action = context.MetaData as ActionMetaData;
            if (action != null)
            {
                switch (action.ActionType)
                {
                    case Metadata.Entity.ActionType.CDO:
                        {
                            if (action.Method.IsEnableTransaction)
                                engine =  new ActionTransExecuteEngine();
                            else
                                engine = new ActionExecuteEngine();
                            if (context.ActionType == SPI.ActionType.CDO_BatchDelete
                                || context.ActionType == SPI.ActionType.CDO_BatchUpdate
                                || context.ActionType == SPI.ActionType.CDO_BatchCreate
                                || context.ActionType == SPI.ActionType.CDO_BatchEditUpdate
                                )
                                engine.SubEngine = new ActionExecuteEngine();
                        }
                        break;
                    default:
                        engine = new ActionExecuteEngine();
                        break;
                }
            }
            else
                engine = new ActionExecuteEngine();
            return engine;
        }

        public static IActionExecuteEngine CreateTransistEngine(ActionExecContext context, ActionExecuteEngineConfig config)
        {
            var action = ActionRTPUtil.ActionMetadataValid(context.MetaData);
            switch (action.ActionType)
            {
                case Metadata.Entity.ActionType.CDO:
                    return new ActionTransExecuteEngine(config);
                default:
                    return new ActionExecuteEngine(config);
            }
        }

    }
}
